package ua.exchangeratesukraine.actions;

import ua.exchangeratesukraine.util.Util;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class WorkDB {

	private String			LOG_TAG		= getClass().getSimpleName();
	private	String			tableName	= "";
	private DBHelper		dbHelper	= null;
	private ContentValues	cv			= null;
	private Context			context		= null;
	private SQLiteDatabase	db			= null;

	public WorkDB() {}

	public void createDB(Context ctx) {
		context = ctx;
		dbHelper = new DBHelper(context);
	}

	public void createTable(String tableName) {
		db = dbHelper.getWritableDatabase();
		dbHelper.addTable(db, tableName);
		dbHelper.close();
	}

	@SuppressWarnings("unchecked")
	public Object read(String date, String tableName, String currencyType) {

		long time = Util.stringToLong(date);
		Log.d(LOG_TAG, "date to DB = " + date + "; time = " + time + "; type = " + currencyType);
		db = dbHelper.getWritableDatabase();

		String query = "";
		if(currencyType.isEmpty())
			query = "time = " + time; // NBU or Banks
		else
			query = "time = " + time + " and " + "type = '" + currencyType + "'"; // Banks
		
		Cursor c = db.query(tableName, null, query, null, null, null, null);
		Log.d(LOG_TAG, "Cursor c = " + c.getCount());
		if (c.moveToFirst()) {
			int valueColIndex = c.getColumnIndex("value");
			byte[] objOut = c.getBlob(valueColIndex);
			return Util.getObjectFromByteArray(objOut);
		} else
			Log.d(LOG_TAG, "----- 0 rows --- Cursor is Empty -----");

		c.close();
		dbHelper.close();

		return false;

	}

	public void addToDB(Object object, String date, String tableName, String currencyType) {
			
		if(object == null) return;
		
		long time = Util.stringToLong(date);
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		byte[] objIn = Util.getByteArrayFromObject(object);
		cv = new ContentValues();
		cv.put("time", time);
		cv.put("type", currencyType);
		cv.put("value", objIn);
		// getting rowID inserted row
		long rowID = db.insert(tableName, null, cv);
		Log.d(LOG_TAG, "row inserted, ID = " + rowID);
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	public DBHelper getDbHelper() {
		return dbHelper;
	}
}